//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/.
// 			VisualNovelToolkit		     /_/_/_/_/_/_/_/_/_/.
// Copyright ©2013 - Sol-tribe.	/_/_/_/_/_/_/_/_/_/.
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/.
using UnityEngine;
using System.Collections;

namespace ViNoToolkit{

	/// <summary>
	/// Title Controller. 
	/// </summary>
	public class TitleCtrl : MonoBehaviour {	
	#region Set up in inspector
		public bool playMusicOnEnter;
		public bool fadeInAtStart = true;
		public string musicResourcePath = "BGM/";

		// View.
		public GameObject target;

		[Range( 0f , 5f)]
		public float panelFadeTime = 1f;

	#endregion

	#region Properties
		static public TitleCtrl Instance{
			get{
				if( m_Instance == null ){
					m_Instance = GameObject.FindObjectOfType(typeof(TitleCtrl)) as TitleCtrl;
				}
				return m_Instance;
			}
		}
	#endregion			
			
	#region PrivateMembers
		static private TitleCtrl m_Instance;
	#endregion

	#region PublicMethods

		void Start(){
			if( fadeInAtStart ){
				Show();
			}
		}

		public void DoNewGame(){
			StartCoroutine ( "_FadeoutAndNewGame" );
		}

		public void QuitApplication(){
			StartCoroutine( "_APPLICATION_QUIT" );
		}

		public void Show(){
			StartCoroutine ( "_Show" );		
		}

		public void DeactiveTitlePanel(){
			StartCoroutine ( "_Deactivate" );		
		}

	#endregion
	#region Private

		IEnumerator _Deactivate(){
			iTween.FadeTo (target, 0f, panelFadeTime );

			yield return new WaitForSeconds ( panelFadeTime );

			target.SetActive (false);
		}

		// Use this for initialization
		IEnumerator _Show () {	
			// Clear Scene.
			// TriggerEvent : [exitscene fade=true].
			Hashtable param = new Hashtable();
			param["fade"] = "true";
			ViNoEventManager.Instance.TriggerEvent( "exitscene" , param );

			// Destroy Currently Scenario Object.
			ScenarioNode snode = ScenarioNode.Instance;
			if( snode != null ){
				DestroyImmediate( snode.gameObject );			
			}

			SystemUIEvent.Instance.menuPanel.SetActive (false);

			if ( playMusicOnEnter ) {
				ISoundPlayer.Instance.PlayMusic( musicResourcePath , true , 0f );
			}

			// Initialize.
			iTween.FadeTo (target, 0f, 0.01f );

			yield return new WaitForSeconds ( 0.5f );

			// Ready to show.
			target.SetActive (true);

			iTween.FadeTo (target, 1f, panelFadeTime );
		}

		IEnumerator _FadeoutAndNewGame( ){
			iTween.FadeTo ( target , 0f , panelFadeTime );

			yield return new WaitForSeconds ( panelFadeTime );

//			ViNoEventManager.Instance.TriggerEvent (sendmessage);
			ViNoAPI.DoNewGame ();

			target.SetActive (false);
		}

		IEnumerator _APPLICATION_QUIT(){

			iTween.FadeTo ( target , 0f , panelFadeTime );

			yield return new WaitForSeconds ( panelFadeTime );

			DestroyImmediate( SystemUIEvent.Instance.systemUIRoot );

			// Destroy.
			DestroyImmediate( target );

			Application.Quit();
		}	
			
	#endregion

	}

}